package com.ptu.servlet;

import com.ptu.entity.*;
import com.ptu.service.DutyService;
import com.ptu.service.impl.DutyServiceImpl;
import org.apache.log4j.helpers.DateTimeDateFormat;
import org.apache.poi.hssf.record.pivottable.StreamIDRecord;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 *
 */
@WebServlet("/ptu/DutyServlet")
public class DutyServlet extends BaseServlet {

    private DutyService dutyService=new DutyServiceImpl();



    //POI数据的导出
    protected void  dutyPOI(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String empid = req.getParameter("empid");

        String deptno = req.getParameter("deptno");

        String dtdate = req.getParameter("dtdate");

        // 符和条件导出的数据集合
        List<Duty> list = dutyService.findMore(empid, deptno, dtdate);

        createExcel(list,resp);
    }


    private static void createExcel(List<Duty> list,HttpServletResponse  resp) {
        // 创建一个Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建一个工作表
        HSSFSheet sheet = workbook.createSheet("考勤表一");

        CellRangeAddress region = new CellRangeAddress(0, // first row
                0, // last row
                0, // first column
                4 // last column
        );
        sheet.addMergedRegion(region);

        HSSFRow hssfRow = sheet.createRow(0);
        HSSFCell headCell = hssfRow.createCell(0);
        headCell.setCellValue("考勤列表");

        // 设置单元格格式居中
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        headCell.setCellStyle(cellStyle);


        // 添加表头行
        hssfRow = sheet.createRow(1);
        // 添加表头内容
        headCell = hssfRow.createCell(0);
        headCell.setCellValue("姓名");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(1);
        headCell.setCellValue("部门");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(2);
        headCell.setCellValue("考勤日期");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(3);
        headCell.setCellValue("签到日期");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(4);
        headCell.setCellValue("签退日期");
        headCell.setCellStyle(cellStyle);

        // 添加数据内容
        for (int i = 0; i < list.size(); i++) {
            hssfRow = sheet.createRow((int) i + 2);
            Duty duty = list.get(i);

            // 创建单元格，并设置值
            HSSFCell cell = hssfRow.createCell(0);
            cell.setCellValue(duty.getRealName());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(1);
            cell.setCellValue(duty.getDeptName());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(2);
            SimpleDateFormat  simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(duty.getDtDate());
            cell.setCellValue(format);
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(3);
            cell.setCellValue(duty.getSigninTime());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(4);
            cell.setCellValue(duty.getSignoutTime());
            cell.setCellStyle(cellStyle);
        }

        // 保存Excel文件
        try {

            //OutputStream outputStream = new FileOutputStream("D:/duty.xls");

            //设置响应的头信息
            resp.setHeader("Content-Disposition", "attachment;filename=duty.xls");

            //设置响应下载的文件类型
            resp.setContentType("application/vnd.ms-excel");

            OutputStream  outputStream=resp.getOutputStream();

            workbook.write(outputStream);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void getMyDuty(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        Employee employee= (Employee) req.getSession().getAttribute("emp");
        String eID=employee.getEmpId();
        String pageNumberStr = req.getParameter("pageNumber");
        int pageNumber = 1; // 开始值
        if(pageNumberStr!=null&&!pageNumberStr.equals("")){
            pageNumber = Integer.parseInt(pageNumberStr);
        }
        PageTools<Duty> dutyAll = (PageTools<Duty>) dutyService.findMyDuty(eID,5,pageNumber);
        req.setAttribute("dutyAll", dutyAll);
        req.getRequestDispatcher("/myDuty.jsp").forward(req, resp);
    }


    // 查询指定用户考勤信息
    protected void  dutyFindMore(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String eID=req.getParameter("eID");
        String date=req.getParameter("date");
        String pageNumberStr = req.getParameter("pageNumber");
        int pageNumber = 1; // 开始值
        if(pageNumberStr!=null&&!pageNumberStr.equals("")){
            pageNumber = Integer.parseInt(pageNumberStr);
        }
        if ((eID==null || eID=="")&&(date==null||date=="")){
            PageTools<Duty> dutyAll = (PageTools<Duty>) dutyService.findAllDuty(5,pageNumber);
            req.setAttribute("dutyAll",dutyAll);
            req.getRequestDispatcher("/dutyList.jsp").forward(req, resp);

        }else {
            PageTools<Duty> dutyAll = (PageTools<Duty>) dutyService.findByIDorDate(eID, date, 5, pageNumber);
            req.setAttribute("eID", eID);
            req.setAttribute("date", date);
            req.setAttribute("dutyAll", dutyAll);
            req.getRequestDispatcher("/dutyList.jsp").forward(req, resp);
        }
    }

    // 用户签退的e操作

    protected void  signOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Date date = new Date();
        //获取系统时间
        SimpleDateFormat format=new SimpleDateFormat("hh:mm:ss");
        SimpleDateFormat format1= new SimpleDateFormat("yyyy-MM-dd");
        //转换为sql时间格式
        Time sqlTime = Time.valueOf(format.format(date));
        java.sql.Date sqlDate = java.sql.Date.valueOf(format1.format(date));
        Employee employee= (Employee) req.getSession().getAttribute("emp");
        String eID=employee.getEmpId();
        if (dutyService.isCheckout(eID,sqlDate.toString(),sqlDate.toString())!=null){
            //执行签到
            if (dutyService.updateDuty(eID,sqlDate,sqlTime)==1){
                req.setAttribute("flag1", 1);
                req.getRequestDispatcher("/dutyAdd.jsp").forward(req, resp);


            }else {
                req.setAttribute("flag1", 0);
                req.getRequestDispatcher("/dutyAdd.jsp").forward(req, resp);


            }

        }else {
            req.setAttribute("flag1", 3);
            req.getRequestDispatcher("/dutyAdd.jsp").forward(req, resp);
        }
    }

    // 用户签到的操作
    protected void  signIn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Date date = new Date();
        //获取系统时间
        SimpleDateFormat format=new SimpleDateFormat("hh:mm:ss");
        SimpleDateFormat format1= new SimpleDateFormat("yyyy-MM-dd");
        //转换为sql时间格式
        Time sqlTime = Time.valueOf(format.format(date));
        java.sql.Date sqlDate = java.sql.Date.valueOf(format1.format(date));
        Employee employee= (Employee) req.getSession().getAttribute("emp");
        String eID=employee.getEmpId();


        if (dutyService.isCheckin(eID,sqlDate.toString(),sqlDate.toString())==null){
            //执行签到
            if (dutyService.addDuty(eID,sqlDate,sqlTime)==1){
//                resp.setHeader("Content-Type","text/javascript;charset=utf-8");
                req.setAttribute("flag", 1);
                req.getRequestDispatcher("/dutyAdd.jsp").forward(req, resp);
//                PrintWriter out=resp.getWriter();
//                out.print("<script> alert('签到成功'); window.location.href=\"/dutyAdd.jsp\"</script>");
            }else {
                req.setAttribute("flag", 0);
                req.getRequestDispatcher("/dutyAdd.jsp").forward(req, resp);
//                resp.setHeader("Content-Type","text/plain;charset=utf-8");
//                PrintWriter out=resp.getWriter();
//                out.print("<script> alert('签到失败'); window.location.href=\"/dutyAdd.jsp\"</script>");

            }



        }else {
            req.setAttribute("flag", 3);
            req.getRequestDispatcher("/dutyAdd.jsp").forward(req, resp);
        }






    }

}
